<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片主体区域  -->
      <el-card>
        <!-- 搜索区域 -->
        <el-form ref="formRef" :model="queryInfo" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="标签名称">
                <el-input v-model="queryInfo.tags" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="城市">
                <el-select placeholder="请选择" @change="changeShowCitys" v-model="value">
                  <el-option
                    v-for="(item,index) in provinces"
                    :key="index"
                    :label="item"
                    :value="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="地区">
                <el-select v-model="defaultCity" placeholder="请选择">
                  <el-option v-for="(item,index) in citys" :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input v-model="queryInfo.shortName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="queryInfo.state" placeholder="请选择">
                  <el-option
                    v-for="item in optionsArray"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item style="margin-left: -40px;">
                <el-button class="dou-btn" @click="clearInfo">清除</el-button>
                <el-button class="dou-btn" @click="searchInfo" type="primary">搜索</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-button
                  size="mini"
                  class="add-btn"
                  icon="el-icon-edit"
                  @click="dialogVisible = true"
                  type="success"
                >新增用户</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- /搜索区域 -->

        <!-- Alert提示框 -->
        <el-alert
          :title="`共${total}条记录`"
          type="info"
          :closable="false"
          @addUser="addUser"
          show-icon
        ></el-alert>
        <!-- /Alert提示框 -->

        <!-- 表格主体区域 -->
        <el-table :data="companysLists" highlight-current-row style="width: 100%">
          <el-table-column label="序号" align="center" prop="id" width="130"></el-table-column>
          <el-table-column label="企业编号" align="center" prop="number" width="130"></el-table-column>
          <el-table-column label="企业简称" align="center" width="100" prop="shortName"></el-table-column>
          <el-table-column label="标签" width="100" align="center" prop="tags"></el-table-column>
          <el-table-column label="创建者" width="100" align="center" prop="creatorID"></el-table-column>
          <el-table-column label="创建日期" align="center" prop="addDate">
            <template slot-scope="scope">{{scope.row.addDate | formatDate}}</template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks"></el-table-column>
          <el-table-column label="状态" align="center" prop="state">
            <template slot-scope="scope">
              <span v-if="scope.row.state === 1">启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template slot-scope="scope">
              <el-button
                type="primary"
                plain
                @click="openEditUser(scope.row)"
                icon="el-icon-edit"
                circle
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                v-if="scope.row.state === 1"
                :enterable="false"
                content="禁用"
                placement="top"
              >
                <el-button
                  type="warning"
                  plain
                  @click="updateState(scope.row)"
                  icon="el-icon-close"
                  circle
                ></el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                v-else
                :enterable="false"
                content="启用"
                placement="top"
              >
                <el-button
                  type="success"
                  plain
                  @click="updateState(scope.row)"
                  icon="el-icon-check"
                  circle
                ></el-button>
              </el-tooltip>

              <el-button
                type="danger"
                plain
                @click="deleteUser(scope.row.id)"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- /表格主体区域 -->

        <el-dialog title="创建用户" :visible.sync="dialogVisible" @close="resetAddDia" width="50%">
          <companys-add
            :dialogVisible="dialogVisible"
            :provinces="provinces"
            @setRef="setRef"
            @setForm="setForm"
            :data="data"
            @changeCity="changeCity"
            :citys="citys"
          />

          <span slot="footer" class="dialog-footer">
            <el-button @click="resetAddDia">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- /添加用户弹框 -->

        <!-- 编辑用户弹框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible" @close="resetEditDia" width="50%">
          <companys-add
            :dialogVisible="dialogVisible"
            :provinces="provinces"
            @setRef="setRef"
            @setForm="setForm"
            :data="data"
            @changeCity="changeCity"
            :citys="citys"
          />

          <span slot="footer" class="dialog-footer">
            <el-button @click="resetEditDia">取 消</el-button>
            <el-button type="primary" @click="editUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- /编辑用户弹框 -->

        <!-- 分页区域 -->
        <pagination
          :queryInfo="queryInfo"
          :total="total"
          @pagination="loadArticleList"
          class="pagina"
        />
      </el-card>
      <!-- /卡片主体区域  -->
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { list as companysList, remove as companysRemove, update as companysUpdate, add as companysAdd, disabled as companysDisabled, detail as companysDetail } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import CompanysAdd from '@/module-hmmm/components/companys-add.vue'
export default {
  name: 'CompanysList',
  data() {
    return {
      companysLists: [], // 企业管理列表
      // 启用和禁用
      optionsArray: [
        {
          value: 1,
          label: '启用'
        },
        {
          value: 0,
          label: '禁用'
        }
      ],
      // 搜索框请求参数
      queryInfo: {
        tags: '',
        shortName: '',
        state: null,
        page: 1,
        pagesize: 10
      },
      refForm: '',
      data: {},
      total: 0,
      // 对话框中的form数据
      dialogForm: {
        isFamous: true,
        shortName: '',
        company: '',
        tags: '',
        remarks: '',
        province: '',
        city: '',
        number: null
      },
      // 判断是添加还是编辑的状态位
      state: true,
      // 省市数据
      provinces: [],
      citys: [],
      // 城市地区选择框绑定的值
      value: '',
      defaultCity: '', // 地区下拉框默认显示的数据
      dialogVisible: false, // 添加弹框
      editDialogVisible: false // 编辑弹框
    }
  },
  created() {
    // 调用获取企业管理列表
    this.getCompanysLists()

    // 省数据赋值
    this.provinces = provinces()
  },
  methods: {
    // 获取企业管理列表
    async getCompanysLists() {
      const { data } = await companysList(this.queryInfo)
      // 将数组赋值给表格的 data
      this.companysLists = data.items
      this.total = data.counts
    },

    // 切换分页刷新列表
    loadArticleList() {
      this.getCompanysLists()
    },

    // select改变时显示对应的城市
    changeShowCitys(e) {
      // e 是当前 select 的值的索引
      this.citys = citys(this.provinces[e])
      // 将地区的第一个自动显示出来
      this.defaultCity = this.citys[0]
    },

    // 重置按钮
    clearInfo() {
      this.queryInfo.state = null
      this.queryInfo.shortName = this.queryInfo.tags = this.value = this.defaultCity = ''
    },

    // 删除用户
    async deleteUser(id) {
      // 删除之前提示
      const ret = await this.$confirm('删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 如果确认删除
      if (ret === 'confirm') {
        // 发送请求
        await companysRemove({ id: id })
        // 提示
        this.$message.success('成功删除用户')
      } else {
        // 不删除
        this.$message.info('您已取消删除')
      }

      // 刷新列表
      this.getCompanysLists()
    },

    // 搜索功能
    async searchInfo() {
      const { data } = await companysList(this.queryInfo)
      // 将数组赋值给表格的 data
      this.companysLists = data.items
      this.total = data.items.total
    },

    // 新增用户弹框重置功能
    resetAddDia(dialogFormRef) {
      // 重置表单以及验证
      this.refForm.resetFields()
      // 清除citys
      this.citys = []
      // 关闭弹框
      this.dialogVisible = false
    },

    // 编辑用户弹框重置功能
    resetEditDia() {
      // 重置表单以及验证
      this.refForm.resetFields()
      this.dialogForm.province = this.dialogForm.city = ''
      this.editDialogVisible = false
    },

    // 接受子组件表单的ref值
    setRef(e) {
      this.refForm = e
    },

    // 接受子组件的form值，用来发送请求
    setForm(e) {
      this.dialogForm = e
    },

    // 新增用户
    addUser() {
      this.state = true
      this.dialogVisible = true
      this.sendReq()
    },

    // 打开编辑弹框
    async openEditUser(userinfo) {
      this.state = false
      // 打开
      this.editDialogVisible = true
      // 获取一行数据
      const { data } = await companysDetail(userinfo)
      // 将数据赋值
      this.data = data
    },

    // 修改用户
    editUser() {
      this.sendReq()
    },

    // 发送添加或者编辑的请求
    async sendReq() {
      if (this.stateValue) {
        // 发送添加请求
        // 对标单进行预校验
        this.refForm.validate(async valid => {
          // 不符合则返回出去
          if (!valid) return
          // 符合规则，发送请求
          await companysAdd(this.dialogForm)
          // 成功提示
          this.$message.success('添加用户成功！')
          // 刷新列表
          this.getCompanysLists()
          // 关闭弹框
          this.dialogVisible = false
        })
      } else {
        // 点击确定发送编辑请求

        // 将值转换为后台需要的类型
        this.dialogForm.isFamous = Boolean(this.dialogForm.isFamous)
        const { data } = await companysUpdate(this.dialogForm)
        // 如果请求失败
        if (!data.success) {
          return this.$message.error('请求失败，请重试')
        }
        // 请求成功
        this.$message.success('修改成功！')
        // 刷新列表
        this.getCompanysLists()
        // 关闭弹框
        this.editDialogVisible = false
      }
    },

    // 更改状态
    async updateState(userinfo) {
      // 如果现在是禁用，则点击启用
      const ret = await this.$confirm('已成功启用, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 判断状态
      if (ret === 'confirm') {
        // 请求之前切换状态
        if (userinfo.state === 1) {
          userinfo.state = 0
        } else {
          userinfo.state = 1
        }

        // 发送请求
        await companysDisabled({ id: userinfo.id, state: userinfo.state })
        this.$message.success('更新状态成功！')
      } else {
        this.$message.info('您已取消操作！')
      }
      // 刷新列表
      this.getCompanysLists()
    },

    // 弹框中的change事件
    changeCity($event) {
      this.citys = $event
    }
  },
  computed: {
    // // 总条数
    // total() {
    //   return this.companysLists.length
    // },

    // 监听状态位
    stateValue() {
      return this.state
    }
  },

  components: {
    CompanysAdd,
    Pagination
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  .app-container {
    .add-btn {
      float: right;
    }
    .dou-btn {
      padding: 9px 15px;
    }
    .el-table {
      margin-top: 20px;
    }
    .selectCls {
      margin-left: 36px;
    }
    .ipt {
      width: 480px;
    }
    ::v-deep .el-dialog__body {
      padding: 30px 50px;
    }
    ::v-deep .el-form-item__label {
      margin-right: !important 6px;
    }
    ::v-deep .el-dialog__footer {
      text-align: center;
    }
    .pagina {
      margin: 20px 0;
      float: right;
    }
  }
}
</style>
